package org.xmx0632.connector.service.jms;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.ObjectMessage;
import javax.jms.Session;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.xmx0632.connector.protocol.processor.MessageProcessor;
import org.xmx0632.connector.util.SpringContextHolder;

/**
 * TODO 5.4 控制指令下发流程
 * 
 */
public class JmsMessageQueueReciver extends MessageListenerAdapter {
	private static final Logger log = LoggerFactory.getLogger(JmsMessageQueueReciver.class);

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void onMessage(Message message, Session session) throws JMSException {
		log.debug("session:{}", session.toString());
		if (message instanceof ObjectMessage) {
			ObjectMessage objectMessage = (ObjectMessage) message;
			Object object = objectMessage.getObject();

			if (object instanceof Message) {
				org.xmx0632.connector.protocol.message.Message request = (org.xmx0632.connector.protocol.message.Message) object;
				log.debug("request:{}", request.toString());
				// 处理下发指令消息
				MessageProcessor messageHandler = SpringContextHolder.getMessageProcessor(request);
				try {
					messageHandler.execute(request);
				} catch (Exception e) {
					log.error(e.getMessage(), e);
				}
				return;
			}

			log.warn("unknown request:{} from activemq", object);
		}
	}
}